from flask import Blueprint, jsonify
from application.models.users.user import User
from util.captcha.captcha import captcha
user_blue = Blueprint("userblue",__name__)
from flask import request,make_response
from util.myredis import r
import json
import time
from db import db
from util.myjwt import myjwt
# 获取图片验证码
@user_blue.route("/ImageCode")
def getImageCode():
    # 调用captcha生成图片验证码
    name, text, img = captcha.generate_captcha()
    # 存入redis 字符串 key :uuid value:text
    uuid = request.args.get('uuid')
    r.str_setex(uuid, text, 300)
    res = make_response(img)
    res.headers['Content-Type'] = "image/jpg"
    return res
# 登录
@user_blue.route("/login", methods=["POST"])
def login():
    # 获取手机号和验证码
    data = json.loads(request.data)
    mobile = data["mobile"]
    code = data["code"]
    print(mobile)
    # 获取验证码进行判断
    codemes = r.str_get(mobile)
    if codemes:
        if str(codemes.decode()) != str(code):
            return jsonify({"code": 10030, "msg": "验证码错误"})
        # 清除验证码
        r.del_key(mobile)
        # 通过手机号查询数据库
        sql = "select * from users where mobile='%s'" % (mobile)
        user = db.findone(sql)
        # 返回用户信息
        if user:
            # 调用jwt、encode生成token
            data = {"data": {"userid": user["id"], "mobile": [
                "mobile"], "exptime": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code": 200, "msg": "登陆成功", "token": token, "userid": user["id"]})
        return jsonify({"code": 201, "msg": "没有该用户"})